import React from 'react';
import {Badge, Button, DatePicker, Drawer, Form, InputNumber, Select, Space} from "antd";
import {useReimburseAndState} from "./DetailsComponent";
import LogFactory from "log/LogFactory";
import {useParams} from "react-router-dom";
import {ReimburseDetailsType} from "type/ReimburseDetailsType";
import locale from "antd/es/date-picker/locale/zh_CN";
import TextArea from "antd/es/input/TextArea";
import dayjs from "dayjs";
import {compareObject} from "util/compare";
import {fetchGetItemOptions, fetchUpdateDetails} from "../../../../redux/reducer/async/detailsAsyncAction";

const log = LogFactory.getLog("Reimburse.DetailsUpdate");
const DetailsUpdateComponent = () => {

    const {detailsId} = useParams();
    const {reimburseId, state, dispatch, navigate, message} = useReimburseAndState();
    const [form] = Form.useForm<ReimburseDetailsType>();
    const [loading, setLoading] = React.useState(false);
    const detailsRef = React.useRef<ReimburseDetailsType>();

    const onClose = () => navigate(".", {replace: true, state: {reimburseId, totalAmount: state.totalMoney}});
    /**
     * 当Drawer打开时,从服务器获取报销记录item-option,填充表单
     */
    const afterOpenChange = async () => {
        if (detailsId === void 0) {
            return;
        }
        let details = state.data.find(d => d.id === parseInt(detailsId));
        if (details === void 0) {
            return;
        }
        if (!state.itemOptions) {
            log.debug("等待从服务器获取报销记录item-option");
            await dispatch(fetchGetItemOptions()).unwrap();
        }
        detailsRef.current = details;
        form.setFieldValue("item", details.item);
        form.setFieldValue("consumeMoney", details.consumeMoney);
        form.setFieldValue("consumeDate", dayjs(details.consumeDate, "YYYY-MM-DD"));
        form.setFieldValue("remark", details.remark);
    };

    const onFinish = async (values: ReimburseDetailsType) => {
        values.consumeDate = values.consumeDate.format("YYYY-MM-DD");
        let compRes = compareObject(detailsRef.current,values) ;
        if (!compRes) {
            message.info("报销记录没有修改");
            return;
        }
        compRes.id = parseInt(detailsId as string);
        setLoading(true);
        let res = await dispatch(fetchUpdateDetails(compRes)).unwrap();
        if (res.data > 0) {
            message.success("修改报销记录成功");
        } else {
            log.debug("修改报销记录失败: ", values);
            message.error("修改报销记录失败");
        }
        setLoading(false) ;
    };

    return (
        <Drawer
            title={"修改报销记录"}
            afterOpenChange={afterOpenChange}
            destroyOnClose={true}
            open={true}
            onClose={onClose}
            maskClosable={false}
            extra={ <Badge status={loading ? "processing" : "success"} />}
        >
            <Form<ReimburseDetailsType>
                form={form}
                layout="vertical"
                onFinish={onFinish}
            >
                <Form.Item<ReimburseDetailsType> name={"item"} label="报销项目"
                                                 rules={[{required: true, message: 'Please select option'}]}>
                    <Select
                        placeholder="Please enter item"
                        options={state.itemOptions}
                        loading={!state.itemOptions}
                        disabled={!state.itemOptions}
                    />
                </Form.Item>
                <Form.Item<ReimburseDetailsType> name={"consumeMoney"} label="消费金额"
                                                 rules={[{required: true, message: 'Please enter consumeMoney'}]}>
                    <InputNumber min={0.00} precision={2} addonBefore={"¥"}/>
                </Form.Item>
                <Form.Item<ReimburseDetailsType> name={"consumeDate"} label="消费时间"
                                                 rules={[{required: true, message: 'Please enter consumeDate'}]}>
                    <DatePicker locale={locale} format={"YYYY-MM-DD"}/>
                </Form.Item>
                <Form.Item<ReimburseDetailsType> name={"remark"} label="备注信息">
                    <TextArea rows={2}/>
                </Form.Item>
                <Form.Item
                >
                    <Space>
                        <Button loading={loading} type="primary" htmlType="submit">
                            提交修改
                        </Button>
                        <Button type="link" htmlType="button">
                            Fill form
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </Drawer>
    );
};

export default DetailsUpdateComponent;